import { Button, message, Modal, Input } from 'antd';
import React, { useState, useRef, useContext } from 'react';
import ProTable from '@ant-design/pro-table';
import AddForm from './components/AddForm';
import { UserContext } from '@/layouts/UserProvider';
import { addList, getList, updateList, removeList } from './service';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const TableList = (props) => {
  const [updateModalVisible, handleDetailModalVisible] = useState(false);
  const [type, setType] = useState('');
  const actionRef = useRef();
  const userCtx = useContext(UserContext);
  const userType = userCtx?.userInfo?.type ?? '';
  const permits = userCtx.userPermits;

  console.log('*****userCtx*********');
  console.log(userCtx);
  console.log(userType);
  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');
    try {
      await addList({
        type: 1,
        name: fields.name,
        phone: fields.phone,
      }).then((data) => {
        hide();
        if (data.code == '200') {
          message.success('添加成功');
          handleDetailModalVisible(false);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error('添加失败请重试！');
        }
      });
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
    }
  };
  /**
   * 编辑
   */
  const handleEdit = async (fields, v) => {
    const hide = message.loading('正在编辑');
    try {
      const res = await updateList({
        type: 1,
        name: fields.name,
        phone: fields.phone,
        id: v.id,
      });
      hide();
      if (res.code == '200') {
        message.success('编辑成功');
        handleDetailModalVisible(false);
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error('编辑失败请重试！');
      }
    } catch (error) {
      hide();
      message.error('编辑失败请重试！');
    }
  };
  const handleDelPermits = (record) => {
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      content: '是否要删除？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        removeList({ id: record.id }).then((data) => {
          console.log('*******删除******');
          console.log(data);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        });
      },
    });
  };
  const columns = [
    {
      title: '司机姓名',
      dataIndex: 'name',
      renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
        if (status === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            // value 和 onchange 会通过 form 自动注入。
            <Input
              // 自定义配置
              placeholder="请输入"
              maxLength={256}
            />
          );
        }
        return defaultRender(_);
      },
    },

    {
      title: '联系方式',
      dataIndex: 'phone',
      renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
        if (status === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            // value 和 onchange 会通过 form 自动注入。
            <Input
              // 自定义配置
              placeholder="请输入"
              maxLength={11}
            />
          );
        }
        return defaultRender(_);
      },
    },

    {
      title: '创建时间',
      search: false,
      dataIndex: 'create_time',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        let res = [];
        if (permits.includes('detailSysMember')) {
          res.push(
            <Button
              size="small"
              key="search"
              onClick={() => {
                handleDetailModalVisible(record);
                setType(2);
              }}
            >
              查看
            </Button>,
          );
        }
        if (permits.includes('updateSysMember')) {
          res.push(
            <Button
              size="small"
              key="edit"
              onClick={() => {
                handleDetailModalVisible(record);
                setType(1);
              }}
            >
              编辑
            </Button>,
          );
        }
        if (permits.includes('deleteSysMember')) {
          res.push(
            <Button size="small" key="detail" onClick={() => handleDelPermits(record)}>
              删除
            </Button>,
          );
        }

        return res;
      },
    },
  ];
  return (
    <>
      <ProTable
        actionRef={actionRef}
        rowKey="key"
        search={{
          collapsed: false,
          defaultCollapsed: false,
          labelWidth: 120,
          searchText: '搜索',
        }}
        request={async (params, sorter, filter) => {
          try {
            console.log('*****params*******');
            console.log(params);
            params.type = 1;
            params.is_total = true;
            params.limit = params.pageSize;
            params.offset = (params.current - 1) * params.pageSize;
            let res = await getList({ ...params, sorter, filter });
            if (res.data == null && res.total != 0) {
              params.current = params.current - 1;
              params.offset = (params.current - 1) * params.pageSize;
              res = await getList({ ...params, sorter, filter });
            }
            return {
              data: JSON.stringify(res.data) != '{}' ? res.data : [],
              success: true,
              total: res.total || 0,
            };
          } catch (error) {
            return { data: [], success: false, total: 0 };
          }
        }}
        columns={columns}
        toolBarRender={() => {
          let res = [];
          if (permits.includes('addSysMember')) {
            res.push(
              <Button
                type="primary"
                key="primary"
                onClick={() => {
                  handleDetailModalVisible(true);
                  setType(0);
                }}
              >
                添加司机
              </Button>,
            );
          }
          return res;
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          hideOnSinglePage: false,
          showTotal: (total) => `共有 ${total} 条记录`,
          pageSize: 10,
        }}
      />
      <AddForm
        onSubmit={async (value) => {
          //添加
          if (type == 0) {
            await handleAdd(value);
          }
          //编辑
          if (type == 1) {
            await handleEdit(value, updateModalVisible);
          }
        }}
        onCancel={() => {
          handleDetailModalVisible(false);
        }}
        type={type}
        updateModalVisible={updateModalVisible}
      />
    </>
  );
};

export default TableList;
